﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using BSDS.Commands.Configuration;
using BSDS.Core.Infrastructure.Logging;

namespace BSDS.Commands.Mailing
{
    public class MailSender
    {
        private readonly SmtpConfiguration configuration;
        private readonly Logger logger;

        private readonly List<string> recipients;

        public MailSender(List<string> recipients, SmtpConfiguration configuration, Logger logger)
        {
            this.recipients = recipients;
            this.configuration = configuration;
            this.logger = logger;
        }

        public void Send(string subject, string body)
        {
            logger.Log(string.Format("Sending mail notificatication."));

            var message = CreateMessage(subject, body);

            using (var smtpClient = new SmtpClient(configuration.SmtpServer, configuration.SmtpPort))
            {
                smtpClient.UseDefaultCredentials = false;
                var credentials = new NetworkCredential(configuration.SenderAccount, configuration.SenderPassword);
                smtpClient.Credentials = credentials;
                smtpClient.EnableSsl = configuration.EnableSsl;
                smtpClient.Timeout = (int)configuration.SmtpTimeout.TotalMilliseconds;
                try
                {
                    smtpClient.Send(message);
                }
                catch (Exception e)
                {
                    logger.Log(e.Message);
                    throw (e);
                }
            }
        }

        private MailMessage CreateMessage(string subject, string body)
        {
            var message = new MailMessage
                              {
                                  From = new MailAddress(configuration.SenderAccount), 
                                  Subject = subject, 
                                  Body = body
                              };
            recipients.ForEach(r => message.To.Add(r));

            return message;
        }
    }
}